import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userGetInfoService, userLogoutService } from '@/api/user.js'

// 用户模块 token setToken removeToken
export const useUserStore = defineStore(
  'tda-user',
  () => {
    const token = ref('')
    const setToken = (newToken) => {
      token.value = newToken
    }
    const removeToken = () => {
      token.value = ''
    }
    const user = ref({})
    const getUser = async () => {
      const res = await userGetInfoService() //请求获取数据
      user.value = res.user
      return user.value
    }
    const setUser = (obj) => {
      user.value = obj
    }
    const logout = async () => {
      const res = await userLogoutService()
      setUser(null)
      removeToken()
    }
    return {
      token,
      setToken,
      removeToken,
      user,
      getUser,
      setUser,
      logout
    }
  },
  {
    // 持久化
    persist: true
  }
)
